package com.pomelo.tiku;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.pomelo.tiku.constants.Constants;
import com.pomelo.tiku.managers.ActivityManager;
import com.pomelo.tiku.receivers.NetWorkChangeReceiver;
import com.tencent.bugly.crashreport.CrashReport;

/**
 * @author liuxiangwang
 * @date .
 */
public class App extends Application {
    private NetWorkChangeReceiver mReceiver;
    private  static Context mContext;
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        registerActivityLifecycle();
        initNetChangeReceiver();
        initBugly();
    }

    public static Context getContext() {
        return mContext;
    }
    private void initNetChangeReceiver() {
        mReceiver = new NetWorkChangeReceiver();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
    }

    private void initBugly() {

        CrashReport.initCrashReport(mContext, Constants.BUGLY_APPID, BuildConfig.DEBUG);
    }

    private void registerActivityLifecycle() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
                ActivityManager.getInstance(mContext).addActivity(activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                ActivityManager.getInstance(mContext).finishActivity(activity);
            }
        });
    }



    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterReceiver(mReceiver);
    }
}
